#coding=utf8
import urllib2, re, urlparse

def getpagenum(content):
    "get the chapters pagenum"
    '''第(1/17)页 跳转到第'''
    s = r"第\(1/(\d*?)\)页 跳转到第"
    s = s.decode('utf-8').encode('gbk')
    numre = re.compile(s)
    if numre.findall(content):
        return int(numre.findall(content)[0])
    else:
        return 0

def pagegenerate(url,content,pagenum):
    pageurl = []
    pageurl.append(url)
    if pagenum:
        urlhead = url[0:-2]
        urltail = '/'
        for i in range(2,pagenum):
            pageurl.append(urlhead+str(i)+urltail)
    return pageurl
    
            
def parserpic(attrs):
    # re1 = re.compile(r"<td><a href=\"(.+)\"><img src=\"(.+)\" alt=\"(.+)\" border=\"0\" /></a></td>")
    re1 = re.compile(r"<td class=\"image\"><img src=\"(.*?)\" border=\"0\" /></td>")
    result = re1.findall(attrs)
    if result:
        return result[0]
    else:
        return None

def getpiclist(url,title='unamed',mylog=None):
    piclist = []

    content = urllib2.urlopen(url).read()
    pagenum = getpagenum(content)
    pageurl = pagegenerate(url,content,pagenum)

    for i in range(0,len(pageurl)):
        content = urllib2.urlopen(pageurl[i]).read()
        item = parserpic(content)
        if item:
            piclist.append([item,item,title])
    
    if item:
        piclist.append([item,item,title])
    return piclist
